import 'package:enjoy_plus/models/add_house.dart';
import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/logger.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:enjoy_plus/utils/upload_image.dart';
import 'package:flutter/material.dart';
import 'package:enjoy_plus/models/house/house_detail.dart';

class AddHouseFrom extends StatefulWidget {
  const AddHouseFrom(
      {super.key,
      required this.community,
      required this.building,
      required this.room,
      // id可选传入，用于编辑房屋信息
      this.id,
      this.isEdit = false});
  final String? community;
  final String? building;
  final String? room;
  final String? id;
  final bool? isEdit;

  @override
  State<AddHouseFrom> createState() => _AddHouseFromState();
}

class _AddHouseFromState extends State<AddHouseFrom> {
  //表单数据
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  String _gender = '男';
  String? _idCardFront;
  String? _idCardBack;
  bool isLoading = false;
  HouseDetailData? _houseDetail;

  //表单校验函数
  bool _validateForm() {
    if (_nameController.text.isEmpty) {
      ToastUtil.showError('请输入姓名');
      return false;
    }
    if (_phoneController.text.isEmpty) {
      ToastUtil.showError('请输入手机号');
      return false;
    }

    // 添加手机号正则验证
    final RegExp phoneReg = RegExp(r'^1[3-9]\d{9}$');
    if (!phoneReg.hasMatch(_phoneController.text)) {
      ToastUtil.showError('请输入正确的手机号格式');
      return false;
    }

    if (_idCardFront == null || _idCardBack == null) {
      ToastUtil.showError('请上传身份证照片');
      return false;
    }

    return true;
  }

  //提交事件
  Future<void> _submit() async {
    if (!_validateForm()) {
      return;
    }
    //TODO:提交审核
    ToastUtil.showSuccess('提交审核中...');
    // logger.d({
    //   'point': widget.community,
    //   'building': widget.building,
    //   'room': widget.room,
    //   'name': _nameController.text,
    //   'gender': _gender == '男' ? 1 : 0,
    //   'mobile': _phoneController.text,
    //   'idcardBackUrl': _idCardBack,
    //   'idcardFrontUrl': _idCardFront,
    // });
    try {
      final res = await http.post<AddHouseData>(
        '/room',
        data: {
          'point': widget.community,
          'building': widget.building,
          'room': widget.room,
          'name': _nameController.text,
          'gender': _gender == '男' ? 1 : 0,
          'mobile': _phoneController.text,
          'idcardBackUrl': _idCardBack,
          'idcardFrontUrl': _idCardFront,
        },
        fromJson: (json) => AddHouseData.fromJson(json),
      );
      if (res.code == 10000) {
        ToastUtil.showSuccess('提交审核成功');
        //提交审核成功后，返回至房屋列表
        if (widget.isEdit ?? false) {
          Navigator.pop(context);
          eventBus.fire(RefreshHouseDetail());
          eventBus.fire(RefreshRoomList());
        } else {
          Navigator.popUntil(context, (route) => route.isFirst);
        }
      } else {
        ToastUtil.showError('返回数据' + res.message);
      }
    } catch (e) {
      ToastUtil.showError('提交审核失败: $e');
    }
  }

  //上传身份证照片
  selectIdCard(bool isFront) async {
    String? imageUrl = await UploadImage.selectAvatar(context);
    logger.d('imageUrl: $imageUrl');
    if (imageUrl != null) {
      setState(() {
        if (isFront) {
          _idCardFront = imageUrl;
        } else {
          _idCardBack = imageUrl;
        }
      });
    }
  }

  //获取房屋信息
  Future<void> getHouseDetail() async {
    setState(() => isLoading = true);
    try {
      final res = await http.get<HouseDetailData>(
        '/room/${widget.id}',
        fromJson: (json) => HouseDetailData.fromJson(json),
      );
      if (res.code == 10000) {
        setState(() {
          _houseDetail = res.data;
          isLoading = false;
          _nameController.text = res.data.name;
          _phoneController.text = res.data.mobile;
          _gender = res.data.gender == 1 ? '男' : '女';
          _idCardFront = res.data.idcardFrontUrl;
          _idCardBack = res.data.idcardBackUrl;
        });
      } else {
        setState(() {
          isLoading = false;
        });
      }
    } catch (e) {
      ToastUtil.showError(e.toString());
      setState(() => isLoading = false);
    }
  }

  //初始化
  @override
  void initState() {
    super.initState();
    if (widget.isEdit ?? false) {
      // 获取房屋信息
      ToastUtil.showSuccess('获取房屋信息中...${widget.id}');
      getHouseDetail();
    } else {
      _nameController.text = '蔡小坤';
      _phoneController.text = '18512345678';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.isEdit ?? false ? '编辑房屋信息' : '添加房屋信息'),
        backgroundColor: const Color(0xFFF1F2F6),
        centerTitle: true,
        leading: IconButton(
            onPressed: () => Navigator.pop(context),
            icon: const Icon(Icons.arrow_back_ios)),
      ),
      body: Container(
        color: const Color(0xFFF1F2F6),
        child: isLoading
            ? const Center(child: CircularProgressIndicator(color: Colors.blue))
            : ListView(
                children: [
                  const Padding(
                    padding: EdgeInsets.all(12),
                    child:
                        Text('房屋信息', style: TextStyle(color: Colors.black45)),
                  ),
                  Container(
                    padding: const EdgeInsets.all(12),
                    color: Colors.white,
                    child: Text(
                        '${widget.community}${widget.building} ${widget.room}',
                        style: const TextStyle(
                            fontSize: 14, color: Colors.black87)),
                  ),
                  const Padding(
                    padding: EdgeInsets.all(12),
                    child:
                        Text('业主信息', style: TextStyle(color: Colors.black45)),
                  ),
                  //姓名
                  Container(
                    padding: const EdgeInsets.all(12),
                    color: Colors.white,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Expanded(flex: 1, child: Text('姓名')),
                        Expanded(
                            flex: 4,
                            child: TextField(
                              controller: _nameController,
                              cursorColor: Colors.blue,
                              style: const TextStyle(fontSize: 14),
                              decoration: const InputDecoration.collapsed(
                                  hintText: '请输入姓名'),
                              maxLength: 15,
                            )),
                      ],
                    ),
                  ),
                  //性别
                  Container(
                    padding: const EdgeInsets.only(left: 12, right: 12),
                    color: Colors.white,
                    child: Row(
                      children: [
                        const Expanded(flex: 1, child: Text('性别')),
                        Expanded(
                            flex: 4,
                            child: Row(
                              children: [
                                Radio(
                                  value: '男',
                                  groupValue: _gender,
                                  activeColor: Colors.blue,
                                  onChanged: (value) =>
                                      setState(() => _gender = value!),
                                ),
                                const Text('男'),
                                Radio(
                                  value: '女',
                                  groupValue: _gender,
                                  activeColor: Colors.blue,
                                  onChanged: (value) =>
                                      setState(() => _gender = value!),
                                ),
                                const Text('女'),
                              ],
                            )),
                      ],
                    ),
                  ),
                  //手机号
                  Container(
                    padding: const EdgeInsets.all(12),
                    color: Colors.white,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Expanded(flex: 1, child: Text('手机号')),
                        Expanded(
                            flex: 4,
                            child: TextField(
                              controller: _phoneController,
                              cursorColor: Colors.blue,
                              style: const TextStyle(fontSize: 14),
                              decoration: const InputDecoration.collapsed(
                                  hintText: '请输入手机号'),
                              maxLength: 11,
                            )),
                      ],
                    ),
                  ),
                  const Padding(
                    padding: EdgeInsets.all(12),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('本人身份证照片',
                            style: TextStyle(color: Colors.black45)),
                        Text('请拍摄证件原件，并使照片中证件边缘完整，文字清晰，光线均匀。',
                            style:
                                TextStyle(color: Colors.black45, fontSize: 12)),
                      ],
                    ),
                  ),
                  //人像��照片
                  Container(
                    padding: const EdgeInsets.all(12),
                    width: double.infinity,
                    height: 240,
                    color: Colors.white,
                    child: ElevatedButton(
                      onPressed: () => selectIdCard(true),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.white,
                        fixedSize: const Size(double.infinity, 240),
                        foregroundColor: Colors.blue,
                        elevation: 0,
                        shadowColor: Colors.transparent,
                        shape: const RoundedRectangleBorder(
                          borderRadius: BorderRadius.zero,
                        ),
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          if (_idCardFront == null)
                            const Icon(Icons.add_a_photo_outlined,
                                color: Colors.blue),
                          if (_idCardFront == null)
                            const Text('上传人像面照片',
                                style: TextStyle(
                                    color: Colors.blue, fontSize: 14)),
                          if (_idCardFront != null)
                            Expanded(
                              child: Image.network(
                                _idCardFront ?? '',
                                fit: BoxFit.contain,
                              ),
                            ),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(height: 12),
                  //国徽面照片
                  Container(
                    padding: const EdgeInsets.all(12),
                    width: double.infinity,
                    height: 240,
                    color: Colors.white,
                    child: ElevatedButton(
                      onPressed: () => selectIdCard(false),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.white,
                        fixedSize: const Size(double.infinity, 240),
                        foregroundColor: Colors.blue,
                        elevation: 0,
                        shadowColor: Colors.transparent,
                        shape: const RoundedRectangleBorder(
                          borderRadius: BorderRadius.zero,
                        ),
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          if (_idCardBack == null)
                            const Icon(Icons.add_a_photo_outlined,
                                color: Colors.blue),
                          if (_idCardBack == null)
                            const Text('上传国徽面照片',
                                style: TextStyle(
                                    color: Colors.blue, fontSize: 14)),
                          if (_idCardBack != null)
                            Expanded(
                              child: Image.network(
                                _idCardBack ?? '',
                                fit: BoxFit.contain,
                              ),
                            ),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(height: 12),
                  //提交按钮
                  Container(
                    padding: const EdgeInsets.all(12),
                    color: Colors.white,
                    child: ElevatedButton(
                      onPressed: _submit,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue,
                        fixedSize: const Size(double.infinity, 48),
                      ),
                      child: const Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text('提交审核', style: TextStyle(color: Colors.white)),
                          SizedBox(width: 1),
                          Icon(
                            Icons.check_circle_outline,
                            color: Colors.white,
                            size: 20,
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
      ),
    );
  }
}
